#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include"xh.h"

PriorityQueue Initailize(int MaxElements) {
	/*if (MaxElements < MinElements) {
		MaxElements = MinElements;
	}*/

	PriorityQueue H =(PriorityQueue)malloc(sizeof(struct HeapStruct));
	if (H == NULL) {
		perror("malloc");
		return NULL;
	}

	H->arr =(int *) malloc(sizeof(ElementType) * (MaxElements + 1));
	if (H->arr == NULL) {
		perror("malloc");
		free(H);
	}

	H->capicity = MaxElements;
	H->arr[0] = -999;
	H->size = 0;

	return H;
}

int IsEmpty(PriorityQueue H) {
	return H == NULL ? 0 : H->size == 0;
}

int Isfull(PriorityQueue H) {
	return H == NULL ? 1 : H->size == H->capicity;
}

void Insert(PriorityQueue H, ElementType x) {
	int i = 0;
	if (Isfull(H)) {
		printf("error!");
	}

	for (i = ++H->size; H->arr[i/2] > x; i /= 2) {
		H->arr[i] = H->arr[i / 2];
	}
	H->arr[i] = x;
}

ElementType deletmin(PriorityQueue H) {
	int i, child;
	ElementType minElement, lastElement;
	if (IsEmpty(H)) {
		printf("Heap is Empty!\n");
		return H->arr[0];
	}
	minElement = H->arr[1];
	lastElement = H->arr[H->size];
	for (i = 1; i * 2 <= H->size; i = child) {
		child = i * 2;
			if (child != H->size && H->arr[child + 1] < H->arr[child])
				child++;
			if (lastElement > H->arr[child])
					H->arr[i] = H->arr[child];
			else
				break;
	}
	H->arr[i] = lastElement;
	H->size--;
	return minElement;
}

ElementType Findmin(PriorityQueue H) {
	if (IsEmpty(H)) {
		printf("%d", H->arr[0]);
	}

	return H->arr[1];
}

void Destroy(PriorityQueue H) {
	if (H)
		if (H->arr)
			free(H->arr);
	free(H);
}

void Showprint(PriorityQueue H) {
	int i = 1;
	for (i = 1; i <=H->size; i++) {
		printf("%d ", H->arr[i]);
	}
	printf("\n");
}